package com.itcam.socket_;

import java.io.*;
import java.net.Socket;

/**
 * Author:Cammy.Wu
 * Date:2024-05-15
 * Description:服务端线程————处理客户端请求
 */

public class ServerThread extends Thread {
    InputStream inputStream = null;
    ObjectInputStream objectInputStream = null;
    OutputStream outputStream = null;
    DataOutputStream dataOutputStream = null;

    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            // 3.接收到的操作流
            inputStream = socket.getInputStream();
//        DataInputStream dataInputStream = new DataInputStream(inputStream);
            objectInputStream = new ObjectInputStream(inputStream);

            // 4.读取客户端发来的数据
//        String str = dataInputStream.readUTF();
            User user = (User) objectInputStream.readObject();
//        System.out.println("客户端发来的数据为：" + str);

            // 对对象进行验证
            boolean flag = false;
            if (user.getName().equals("cammy") && user.getPwd().equals("158633115")) {
                flag = true;
            }

            // 向客户端输出一句话 --》 操作流 --》输出流
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
//        dataOutputStream.writeUTF("你好，我是服务器，我接收到了你的请求");
            dataOutputStream.writeBoolean(flag);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 5.关闭流
//        dataInputStream.close();
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
